from django.shortcuts import render

from django.core.cache import cache

from rest_framework.views import APIView
from rest_framework.response import Response
import logging   # 需导包

from home.models import NavCategory,CourseCategory,Image
from home.serializers import NavCategorySerializer,BehindCategorySerializer,ImageSerializer

# Create your views here.


# 以后打印都不需要print了，用logging
logging = logging.getLogger('django')







# 使用APIView是因为它最灵活
class NavCategoryAPIView(APIView):

    def get(self,request):
        try:
            queryset = NavCategory.objects.filter(is_deleted=False,is_show=True)
            serializer = NavCategorySerializer(queryset,many=True)
            logging.info(f'获取分类数据成功，共获取{len(serializer.data)}条')
            return Response({'code':1,'msg':'ok','data':serializer.data})
        except Exception as e:
            logging.error(f'获取分类数据失败，错误信息{e}')
            return Response({'code':0,'msg':'不ok'})



class BehindCategoryAPIView(APIView):

    def get(self,request):

        try:
            cache_key = 'code_mirror:home:behind'
            behind_redis = cache.get(cache_key)
            if behind_redis:
                logging.info('从redis缓存中读取到数据')
                return Response({
                    'code':1,
                    "message": "SUCCESS FROM CACHE",
                    "data": behind_redis
                })
            # 反之redis中没有就找数据库mysql
            queryset = CourseCategory.objects.filter(is_deleted=False,is_show=True,level=1).order_by('level')
            serializer = BehindCategorySerializer(queryset,many=True)
            # 再保存到redis中去
            cache.set(cache_key,serializer.data,timeout=60*60*24)  # 保存24小时一天
            logging.info(f'已从mysql数据库中读取文件到缓存中，获取了{len(serializer.data)}条数据')
            return Response({
                'code':1,
                "message": "SUCCESS FROM MYSQL",
                "data": serializer.data
            })
        except Exception as e:
            logging.error(f'获取分类数据失败，错误信息{e}')
            return Response({'code':0,'msg':'不ok'})



class ImageAPIView(APIView):

    def get(self,request):
        try:
            # 定义redis数据的键-->键取值
            cache_key = 'code_mirror:home:image'
            # get方法获取redis中的数据
            image_redis = cache.get(cache_key)
            # 如果缓存中有这个数据，就进行返回
            if image_redis:
                logging.info('从redis中获取图片数据成功')
                return Response({
                    "code": 1,
                    "message": "SUCCESS FROM CACHE",
                    "data": image_redis
                })

            # 没有的话正常使用mysql查询
            queryset = Image.objects.filter(is_deleted=False,is_show=True)
            serializer = ImageSerializer(queryset,many=True)
            # 把mysql中数据缓存到redis
            cache.set(cache_key, serializer.data, timeout=60 * 60 * 24)
            logging.info(f'成功从MYsql获取轮播图列表,并更新到redis缓存，共获取{len(serializer.data)}条')
            return Response({'code':1,'msg':'SUCCESS from mysql','data':serializer.data})
        except Exception as e:
            logging.error(f'获取图片数据失败，错误信息{e}')
            return Response({'code':0,'msg':'不ok'})
